##
## Figure 1: Boko Haram Area and the Three Countries of Study
##

output_version <- Sys.Date()
outdir <- paste0(wkdir,'/boko_haram_paper/figures')
xfun::dir_create(outdir)

##
adm0_lake_chad_shp = paste0(wkdir,'/local/gis_data/003_boundaries/lake_chad/lake_chad_adm0')
adm0_sf <- read_sf(dirname(adm0_lake_chad_shp), basename(adm0_lake_chad_shp))
adm0_sf = adm0_sf %>%
  dplyr::mutate(Boundary='Country')

adm0_sf_pt <- adm0_sf %>% st_centroid() %>%
  mutate(x = st_coordinates(.)[, 1],  # x coordinate
         y = st_coordinates(.)[, 2])  %>% # y coordinate
  mutate(x = case_when(
    NAME_0 == "Cameroon" ~ 12.5,  
    NAME_0 == "Nigeria" ~ 7.5,
    TRUE ~ x  # Keep the existing value for all other cases
  )) %>%
  mutate(y = case_when(
    NAME_0 == "Cameroon" ~ 5.69,  
    NAME_0 == "Nigeria" ~ 9.5,
    TRUE ~ y  # Keep the existing value for all other cases
  )) %>% 
  # update X and Y
  mutate(geometry = st_sfc(purrr::map2(x, y, ~ st_point(c(.x, .y))), crs = st_crs(.)))


bhbr_dst_fn = paste0(wkdir,'/local/gis_data/003_boundaries/bhbr_dst')
bhbr_sf <- read_sf(dirname(bhbr_dst_fn), basename(bhbr_dst_fn))
bhbr_sf = bhbr_sf %>%
  dplyr::mutate(Boundary='BHBR area')

bhbr_state_fn = file.path(wkdir,'local/gis_data/003_boundaries/gadm36_lake_chad_ctr_1')
bhbr_state_sf <- read_sf(dirname(bhbr_state_fn), basename(bhbr_state_fn))
bh_states <- c("Adamawa","Borno","Yobe")
bhbr_state_sf = bhbr_state_sf %>%
  dplyr::filter(NAME_1 %in% bh_states) %>%
  dplyr::select(GID_0,NAME_0,GID_1,NAME_1,bh3ss) %>%
  dplyr::mutate(Boundary='BHBR state')

bhbr_state_inside_sf <-  st_intersection(bhbr_state_sf,bhbr_sf["geometry"]) %>%
  dplyr::mutate(nudge_x = c(-0.2,0.2,0.2),
                nudge_y = c(-0.2,0.2,0.2)) %>%
  relocate(geometry, .after = last_col()) 

bhbr_state_inside_pt <- st_centroid(bhbr_state_inside_sf)
bhbr_state_inside_pt <-  bhbr_state_inside_pt %>%
  mutate(x = st_coordinates(.)[, 1],      # x coordinate
         y = st_coordinates(.)[, 2])  %>% # y coordinate
  st_drop_geometry()

# separate manual assign of coordinates for map
bhbr_state_inside_pt_yobe <- bhbr_state_inside_pt %>%
  dplyr::filter(NAME_1 == "Yobe") %>%
  dplyr::mutate(x = 11.2, y = 12.6)

bhbr_state_inside_pt_adamawa <- bhbr_state_inside_pt %>%
  dplyr::filter(NAME_1 == "Adamawa") %>%
  dplyr::mutate(x = 11.9, y = 9.5)

bhbr_state_inside_pt_borno <- bhbr_state_inside_pt %>%
  dplyr::filter(NAME_1 == "Borno") %>%
  dplyr::mutate(x = 13, y = 12.7)


bhbr200k_fn = paste0(wkdir,'/local/gis_data/003_boundaries/bhbr_dst200km_neigh_gadm0')
bhbr200k_sf <- read_sf(dirname(bhbr200k_fn), basename(bhbr200k_fn))
bhbr200k_sf <- subset(bhbr200k_sf,NEIGH==1)
bhbr200k_sf = bhbr200k_sf %>%
  dplyr::mutate(Boundary='BHBR 200km',
                pattern = 'stripe',
                pattern_color = "BH200color")

# merge with ntl zones
ntl.zones <- read_sf(dsn=paste0(wkdir,'/local/gis_data/003_boundaries/fishnet'),layer='fishnet_lake_chad_ntl_adm0_x_d01')

cumevents <- readstata13::read.dta13(paste0(wkdir,"/proc_data/ACLED_w_types_0018_ts2.dta"))
cumevents0913 <- cumevents %>%
  dplyr::filter(year %in% 2009:2013)
  
cumevents_sf <- merge(ntl.zones, cumevents0913, by.x="OBJECTID",by.y="objectid",all = TRUE)
dim(cumevents_sf)

maxcumevent <- max(cumevents_sf$bhcumevent,na.rm=T)
vals <- as.numeric(cumevents_sf$bhcumevent)

cumevents_sf2map <- cumevents_sf %>%
  dplyr::mutate(f_bhcumevent = cut(bhcumevent, 
                                   breaks = c(1, 2, 3, 6, 11, 265),
                                   labels = c("1", "2", "3 - 5", "6 - 10", "11 - 265"),
                                   include.lowest = TRUE, 
                                   right = TRUE)
  ) %>%
  dplyr::select(bhcumevent,f_bhcumevent) %>%
  dplyr::filter(!is.na(bhcumevent))

# Get a 5-category red palette
red_palette <- RColorBrewer::brewer.pal(5, "Reds")

windowsFonts("Arial" = windowsFont("Arial"))
mytheme <- theme(text = element_text(family = 'Arial')
                 ,panel.background = element_rect(fill = 'white')
                 ,axis.title = element_blank()
                 ,axis.text = element_blank()
)

##
## plot
##
outfn = file.path(figdir,sprintf('bh_cumevents_and_study_area3states_%s.png',output_version))

#
p1_cumevents3 <- ggplot() +
  geom_sf(data = cumevents_sf2map,
          aes(fill = f_bhcumevent), color = NA) +
  scale_fill_manual(values = red_palette,
                    name = "Total events\n(2009-2013)",
                    guide = guide_legend(order = 1)) +
  
  ggpattern::geom_sf_pattern(data = bhbr200k_sf,
                             aes(pattern = "stripe", pattern_color = "Boko Haram - 200km"),
                             pattern_fill = NA,
                             pattern_angle = 45, 
                             pattern_density = 0.5,
                             fill = NA,
                             pattern_key_scale_factor = 0.5,) +
  
  # Remove the pattern from the legend (but show pattern_color)
  scale_pattern_manual(name = "",
                       values = c("stripe" = "stripe",
                                  "Boko Haram - 200km" = "gray50"),
                       guide = "none") +

  # Use pattern_color for the legend (combine pattern and color in one entry)
  scale_pattern_color_manual(name = "",  # Custom name for the legend
                             values = c("Boko Haram - 200km" = "gray50"),  # Define the pattern color (gray)
                             guide = guide_legend(override.aes = list(pattern = "stripe", 
                                                                      fill = NA), 
                                                  order = 2)) +  # Combine pattern and color in one legend item
  
  geom_sf(data = adm0_sf, aes(color = "C"), fill = NA) +
  geom_sf_label(data = adm0_sf_pt, aes(x = x, y = y, label = NAME_0), 
                color = "black", fontface = "bold", size = 2.5,
                label.size  = NA) +  # Remove padding and background
  
  geom_sf(data = bhbr_state_inside_sf, fill = NA, color = "darkblue", linetype = "dashed") +
  
  ggrepel::geom_label_repel(data = bhbr_state_inside_pt_adamawa,
                   aes(x, y), 
                   label = 'Adamawa',
                   label.size = 0.25,          # No border around label
                   label.r = 0,             # No rounded corners
                   fill = NA,               # No background color for label
                   color = "darkblue", 
                   box.padding = 0.35,  
                   size = 2,
                   min.segment.length = unit(0, 'lines'), 
                   nudge_x = -1.65,
                   nudge_y = -1.25) + 
  
  ggrepel::geom_label_repel(data = bhbr_state_inside_pt_borno,
                            aes(x, y), 
                            label = 'Borno',
                            label.size = 0.25,          # No border around label
                            label.r = 0,             # No rounded corners
                            fill = "white",               # No background color for label
                            color = "darkblue", 
                            box.padding = 0.35,  
                            size = 2,
                            min.segment.length = unit(0, 'lines'), 
                            nudge_x = 0.25,
                            nudge_y = 2.5) + 
  
  ggrepel::geom_label_repel(data = bhbr_state_inside_pt_yobe,
                            aes(x, y), 
                            label = 'Yobe',
                            label.size = 0.25,          # No border around label
                            label.r = 0,             # No rounded corners
                            fill = "white",               # No background color for label
                            color = "darkblue", 
                            box.padding = 0.35,  
                            size = 2,
                            min.segment.length = unit(0, 'lines'), 
                            nudge_x = -0.25,
                            nudge_y = 2.25) + 
  #
  geom_sf(data = bhbr_sf, aes(color = "B"), fill = NA) +
  scale_color_manual(name = "",
                     labels = c("Boko Haram area (BH)", "Country"),
                     values = c("B" = "red", "C" = "gray50"),
                     guide = guide_legend(order = 3)) +
  coord_sf() +
  theme(
    # Replacing legend.position with legend.position.inside
    legend.position = c(0.975, 0.025),  # This is the correct usage: positioning the legend inside the plot
    legend.justification = c(1, 0),
    legend.key.size = unit(0.4, "cm"),
    legend.text = element_text(size = 8),
    legend.title = element_text(size = 9),
    legend.spacing.y = unit(0, "lines"),
    legend.margin = margin(0, 0, 0, 0),
    axis.ticks = element_blank(),  # Remove axis ticks
    axis.text = element_blank(),   # Remove axis labels
    #legend.background = element_rect(color = "black", size = 1, linetype = "solid", fill = "lightgray"), # Border around legend items
    legend.box.background = element_rect(color = "black", size = 0.3, linetype = "solid"),  # Border around entire legend box
    legend.box.margin = margin(4, 4, 4, 4)  # Optional: Add some margin around the entire legend box
    
  ) +
  mytheme

p1_cumevents3

ggsave(filename=outfn,plot=p1_cumevents3,dpi=500,
       width = 6, height = 5.5)
